<template>
  <div id="demo" style="width: 900px;height:800px;"></div>
</template>

<script>
import * as echarts from 'echarts';
import request from '@/utils/request'

export default {
  data() {
    return {
      //  category 分类统计信息
      statisticsCategoryData: [],
      categoryData: [],
      myChart:null, // 存放echarts

    };
  },
  mounted() {
    this.myChart = echarts.init(document.getElementById('demo'));
    this.loadDataAndDrawChart();
  },
  methods: {
    async loadDataAndDrawChart() {
      await this.statisticsCategory(); // 等待数据加载完成
      this.drawChart(); // 数据加载完成后执行绘制图表的操作
    },
    //获取统计数据
    async statisticsCategory() {
      try {
        // 需要进行 await
        const response = await request.get('/category/statisticsCategory');
        console.log(response)
        //统计数据
        this.statisticsCategoryData = response.data.data;
        //分类数据
        this.categoryData = response.data.categoryData;
        this.statisticsCategoryData = Object.keys(this.statisticsCategoryData).map(key => response.data.data[key]);
      } catch (error) {
        console.error('Failed to load data:', error);
      }
    },
    //绘制数据
    drawChart() {
      var option;
      option = {
        title: {
          text: '商品分类数量统计',
          subtext: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        legend: {
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          top: 20,
          bottom: 20,
          //分类名称
          data: this.categoryData
        },
        series: [
          {
            name: '分类名称',
            type: 'pie',
            radius: '55%',
            center: ['40%', '50%'],
            //分类统计属性
            data: this.statisticsCategoryData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      }
      this.myChart.setOption(option)
    },
  }
}
</script>

